import { PageContainer } from '@ant-design/pro-layout';
import { useEffect, useRef, useState } from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import ProForm, { ModalForm, ProFormText, ProFormRadio, ProFormDigit, ProFormDatePicker, ProFormSelect, QueryFilter, ProFormDateRangePicker } from '@ant-design/pro-form';
import { AutoComplete, Button, Col, Form, message, Modal, Row, Statistic, Table } from 'antd';
import { DownOutlined, PlusOutlined } from '@ant-design/icons/lib/icons';
import { createOrder, createDispatchOrder, deleteOrder, queryOrders, updateDispatchOrder, queryContries, queryUsers } from '@/services/ant-design-pro/api';
import { useAccess, Access } from 'umi';
import { contrySelectRequest, userIDSelectRequest } from './common';
import moment from 'moment';


const convertDateToTime = (value) => {
    if (value) {
        let t = Date.parse(value);
        return new Date(t);
    }
    return null
}

const formatTimeToDateString = (value) => {
    if (value) {
        return moment(value).format("YYYY-MM-DD");
    }
    return ""
}
const convertFormValue = (values) => {
    values.order_create_time = convertDateToTime(values.order_create_time)
    values.pay_time = convertDateToTime(values.pay_time)
    values.return_time = convertDateToTime(values.return_time)
    values.refund_time = convertDateToTime(values.refund_time)
    values.final_time = convertDateToTime(values.final_time)
}

export default () => {
    const actionRef = useRef<ActionType>();
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
    const [currentRow, setCurrentRow] = useState<any>();
    const [tableData, setTableData] = useState<any>([]);
    const [customerAutoFillList, setCustomerAutoFillList] = useState<any>([]);
    const access = useAccess();
    const tableRequest = async (
        params: {
            current?: number;
            pageSize?: number;
        },
    ) => {
        let userResp: any = await queryOrders(params);
        setTableData(userResp.data)
        return {
            data: userResp.data,
            success: true,
        }
    }
    useEffect(() => {
        console.log("order access", access)
        tableRequest({})
    }, [])

    useEffect(() => {
        let customerMap = new Map();
        //客户名自动补全
        let customerOptions: { value: any; }[] = [];
        tableData.forEach((val) => {
            customerMap.set(val.customer_name, 1)
        })

        customerMap.forEach((value, key) => {
            customerOptions.push({ value: key });
        });
        setCustomerAutoFillList(customerOptions)
    }, [tableData])
    const columns: ProColumns<AnalyserNode>[] = [
        { title: 'ID', dataIndex: 'id' },
        { title: '国家', dataIndex: 'country', search: true, request: contrySelectRequest },
        { title: '单价', dataIndex: 'price' },
        { title: '客户下单量', dataIndex: 'customer_count' },
        // { title: '实际完成量', dataIndex: 'complete_count' },
        { title: '实际结算量', dataIndex: 'count' },
        { title: '派单备注', dataIndex: 'dispatch_comment' },
        { title: '备注', dataIndex: 'dispatch_user_comment' },
        {

            title: '销售员', dataIndex: 'username',
            render: (text, record, idx) => {
                return record.username + "(" + record.nickname + ")"
            },
            search: access.isAdmin,
            request: userIDSelectRequest
        },
        {
            title: '订单日期',
            dataIndex: 'order_create_time',
            valueType: 'dateRange',
            search: true,
            render: (text, record) => {
                return formatTimeToDateString(record.order_create_time)
            }
        },
        {
            title: '操作',
            valueType: 'option',
            render: (text, record, _, action) => [
                <a
                    key="editable"
                    onClick={() => {
                        handleUpdateModalVisible(true);
                        setCurrentRow(record);
                    }}
                >
                    编辑
                </a>
            ],
        },
    ];
    columns.forEach(column => {
        if (typeof (column.search) == "undefined") {
            column.search = false;
        }
    })
    return <PageContainer>
        <ProTable<any>
            actionRef={actionRef}
            rowKey="id"
            columns={columns}
            request={tableRequest}
            search={true}
            toolBarRender={() => [
                <Button
                    type="primary"
                    key="primary"
                    onClick={() => {
                        handleModalVisible(true);
                    }}
                >
                    <PlusOutlined />新建
                </Button>,
            ]}
        />

        <ModalForm
            title={"新建订单"}
            // width="400px"
            visible={createModalVisible}
            onVisibleChange={handleModalVisible}
            onFinish={async (values) => {
                convertFormValue(values)
                let result = await createDispatchOrder(values)
                if (result.code == 0) {
                    handleModalVisible(false);
                    if (actionRef.current) {
                        actionRef.current.reload();
                    }
                }
            }}
        >
            <ProForm.Group>
                <ProFormText name="dispatch_comment" label="派单备注" width="md" rules={[{ required: true }]} />
                <ProFormSelect name="user_id" width="md" label="销售员"
                    rules={[{ required: true }]}
                    request={userIDSelectRequest}
                />
            </ProForm.Group>
            <ProForm.Group>
                <ProFormSelect name="country" width="md" label="国家"
                    rules={[{ required: true }]}
                    request={contrySelectRequest}
                />
                <ProFormDigit name="price" label="单价" width="md" min={0}
                    rules={[
                        { required: true },
                    ]}
                />
            </ProForm.Group>

            <ProForm.Group>
                <ProFormDigit name="customer_count" label="客户下单量" width="md" min={0} rules={[{ required: true }]} />
                <ProFormDigit name="complete_count" label="实际完成量" width="md" min={0} />
            </ProForm.Group>
            <ProForm.Group>
                <ProFormText name="dispatch_user_comment" label="备注" width="md" />
            </ProForm.Group>
        </ModalForm>

        <Modal
            title="编辑数据"
            visible={updateModalVisible}
            onCancel={() => {
                handleUpdateModalVisible(false)
            }}
            onOk={() => { }}
            okText="确认"
            cancelText="取消"
            destroyOnClose={true}
            footer={null}
        >
            <ProForm onFinish={async (values: any) => {
                convertFormValue(values)
                let result = await updateDispatchOrder(values)
                if (result.code == 0) {
                    handleUpdateModalVisible(false)
                    actionRef.current?.reload();
                    message.success("更新成功")
                }
            }} >
                <ProFormText name="id" width="md" label="ID" initialValue={currentRow?.id} disabled
                    rules={[{ required: true }]}
                />
                <ProFormDigit name="customer_count" label="客户下单量" width="md" min={0} rules={[{ required: true }]} initialValue={currentRow?.customer_count} />
                <ProFormDigit name="complete_count" label="实际完成量" width="md" min={0} initialValue={currentRow?.complete_count} />
                <ProFormText name="dispatch_user_comment" label="备注" width="md" initialValue={currentRow?.dispatch_user_comment} />
            </ProForm>
        </Modal>
    </PageContainer>
};
